/**
 * 
 */
package per.lxy.wechat.util;

import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lixiaoying
 */
public class MyStringUtils {
	/**
	 * 根据空格符切割文本，并获取指定下标内容
	 * 抽取字符串信息
	 * */
	public static String extracTextInfo(String text,int index) {
		if(text == null || "".equals(text.trim())) {
			return "";
		}
		text = text.trim();
		
		String [] arr = text.split("[\\s]+");
		
		if(arr.length > index) {
			try {
				return arr[index];
			} catch (ArrayIndexOutOfBoundsException e) {
				System.out.println("-------------------------------------------------------------");
				System.out.println("数组长度:"+arr.length);
				System.out.println("index:"+index);
				System.out.println(text);
				System.out.println("-------------------------------------------------------------");
			}
		}
		return "";
	}
	
	/**
	 * 格式化主机信息
	 * params [14.17.43.152:80, 180.163.25.150:80]
	 * */
	public static Set<String> formatHostinfo(Set<String> processIds) throws IOException {
		return processIds.stream().map(id->{
			if(id!= null && id.indexOf(":")!=-1) {
				return id.split(":")[0];
			}
			return null;
		}).collect(Collectors.toSet());
	}
	
	private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
 
    public static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
 
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
 
        }
        return d;
    }
	
}
